package com.cjh.controller;


import com.cjh.annotation.WebLog;
import com.cjh.pojo.User;
import com.cjh.service.UserService;
import com.cjh.utils.RedisUtil;
import com.cjh.vo.ResultMap;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/userApi")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/userList")
    @WebLog(description = "请求=>查询所有用户信息接口")
    public ResultMap userList(@RequestParam(value = "page", defaultValue = "1",required = false) Integer page
            , @RequestParam(value = "limit", defaultValue = "10",required = false) Integer limit) {
        PageHelper.startPage(page, limit);
        List<User> users = userService.list();
        PageInfo<User> pageInfo = new PageInfo<>(users);

        return ResultMap.ok(0, "所有用户信息->每页10条数据", pageInfo.getList(), (int) pageInfo.getTotal());
    }

    @PostMapping("/getUser")
    @WebLog(description = "请求=>查询个人信息接口")
    public ResultMap getUser(HttpSession session) {

        User sessionUser = (User) session.getAttribute("user");
        User redisUser = (User) redisUtil.get("user:" + sessionUser.getId());
        if (!Objects.isNull(redisUser)){
            logger.info("===从redis获取===");
            return ResultMap.ok(200, "查询用户信息", redisUser, 1);
        }
        User user = userService.getById(sessionUser.getId());
        redisUtil.set("user:"+user.getId(),user);
        logger.info("===从数据库获取===");
        return ResultMap.ok(200, "查询用户信息", user, 1);
    }

    @PostMapping("/insertUser")
    @WebLog(description = "请求=>添加用户接口")
    public ResultMap insertUser(User user){
        user.setRegisterDate(new Date());
        boolean flag = userService.save(user);
        return ResultMap.ok(200,"添加一个用户","SUCCESS",1);
    }

    @DeleteMapping("/deleteUserById/{id}")
    @WebLog(description = "请求=>删除用户接口")
    public ResultMap deleteUserById(@PathVariable("id") Integer id){
        boolean flag = userService.removeById(id);
        redisUtil.del("user:"+id);
        return ResultMap.ok(200,"根据id删除一个用户","删除成功",1);
    }

    @PutMapping("/updateUserById")
    @WebLog(description = "请求=>修改用户接口")
    public ResultMap updateUserById(User user){
        System.out.println("====消费者====："+user);
        boolean flag = userService.updateById(user);
        redisUtil.set("user:"+user.getId(),user);
        return ResultMap.ok(200,"修改一个用户","保存成功",1);
    }

}
